<template>
  <div class="app-container">
    <el-row :gutter="5" class="mb8">
      <el-form :data="baseDataParam" :inline="true" class="el-form-search">
        <el-col style="display: flex; justify-content: end">
          <!--查询时-->

          <!--设备选择-->
          <el-form-item class="el-form-search-item" label="设备" porp="device">
            <el-select
              v-model="baseDataParam.deviceId"
              clearable
              filterable
              placeholder="请选择设备类型"
              @change="setChannelList"
            >
              <el-option
                v-for="device in deviceList"
                :key="device.zhGuid"
                :label="device.devName"
                :value="device.zhGuid"
              />
            </el-select>
          </el-form-item>
          <!--通道选择-->
          <el-form-item class="el-form-search-item" label="通道" porp="channel">
            <el-select
              v-model="baseDataParam.tdGuid"
              clearable
              filterable
              placeholder="请选择设备类型"
            >
              <el-option
                v-for="channel in channelList"
                :key="channel.tdGuid"
                :label="channel.channelName"
                :value="channel.tdGuid"
              />
            </el-select>
          </el-form-item>
          <!--数据类-->
          <el-form-item label="数据类" prop="dataType">
            <el-select
              v-model="baseDataParam.dataType"
              size="mini"
              placeholder="选择数据类"
              style="width: 120px"
              @change="getMonitoringItem"
            >
              <el-option
                v-for="dict in dataTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="监测项" prop="monitoringItem">
            <el-select
              v-model="baseDataParam.monitoringItem"
              style="width: 120px"
              size="mini"
              placeholder="选择监测项"
            >
              <el-option
                v-for="item in monitoringItemOptions"
                :key="item.field"
                :label="item.comment"
                :value="item.field"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据类型" prop="groupMethod">
            <el-select
              v-model="baseDataParam.groupMethod"
              size="mini"
              style="width: 100px"
              placeholder="选择监测项"
            >
              <el-option
                v-for="dict in groupMethodOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="查询时间" prop="datetime">
            <el-date-picker
              v-model="baseDataParam.datetime"
              type="datetimerange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm"
              size="mini"
              style="width: 340px"
              @change="setDateTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item class="el-form-search-item">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleSearch"
              >搜索
            </el-button>
            <!-- <el-button icon="el-icon-refresh">重置</el-button> -->
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <line-chart
      v-for="(keyName, index) in charComponents"
      :key="keyName"
      :color="index === 0 ? '#465E7A' : index == 1 ? '#03DF6D' : '#FF4408'"
      :ref="`chart${keyName}`"
    />
    <el-empty
      v-show="charComponents.length === 0"
      description="点击搜索查询数据"
    ></el-empty>
  </div>
</template>

<script>
import LineChart from "@/views/dashboard/LineChart4.vue";
import { getFieldInfo } from "@/api/data_analysis/FieldInfo";
import {
  getFlowLineData,
  getFlowDataBase,
} from "@/api/data_analysis/dataAnalysis";
import { mapState } from "vuex";

function debounce(fn, delay, immediate = false) {
  let timer;

  return function (...args) {
    const doItNow = immediate && !timer;
    clearTimeout(timer);

    timer = setTimeout(() => {
      timer = null;
      if (!immediate) {
        fn.apply(this, args);
      }
    }, delay);

    if (doItNow) {
      fn.apply(this, args);
    }
  };
}

export default {
  components: { LineChart },
  data() {
    return {
      /**
       * 搜索框数据
       */
      dateKey: new Date(),
      baseDataParam: {
        deviceId: "",
        tdGuid: "",
        alarmType: "",
        month: "",
        datetime: [new Date("2024", "04", "21"), new Date()],
        dataType: "",
        monitoringItem: "Uat" || "",
        groupMethod: "max",
        dto: {},
      },
      //日期选择框快捷键
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      chartData: {},
      isExcute: false, //是否执行
      //数据类
      dataTypeOptions: [],
      charComponents: [],
      //检测项
      monitoringItemOptions: [],
      monitoringItemFilter: ["XH", "tdGuid"],
      // 聚合类型
      groupMethodOptions: [],
      channelList: [],
    };
  },
  computed: {
    ...mapState({
      deviceList: (state) => state.user.deviceList, // 从 Vuex 中获取 deviceList
    }),
  },
  created() {
    console.log("created", this.$route.meta.title);

    // 获取数据类字典
    this.getDicts("db_data_type").then((response) => {
      this.dataTypeOptions = response.data;

      switch (this.$route.meta.title) {
        case "基本数据":
          this.dataTypeOptions = this.dataTypeOptions.filter((f) =>
            [
              "其他数据",
              "U/I有效值",
              "电流序分量",
              "电压序分量",
              "长时闪变",
              "短时闪变",
              "电压偏差",
            ].includes(f.dictLabel)
          );

          break;
        case "谐波电流":
          this.dataTypeOptions = this.dataTypeOptions.filter((f) =>
            ["电流谐波"].includes(f.dictLabel)
          );
          break;
        case "谐波电压":
          this.dataTypeOptions = this.dataTypeOptions.filter((f) =>
            ["电压谐波"].includes(f.dictLabel)
          );

          break;
        case "间谐波电流":
          this.dataTypeOptions = this.dataTypeOptions.filter((f) =>
            ["电流间谐波"].includes(f.dictLabel)
          );
          break;
        case "间谐波电压":
          this.dataTypeOptions = this.dataTypeOptions.filter((f) =>
            ["电压间谐波"].includes(f.dictLabel)
          );
          break;
      }

      this.baseDataParam.dataType = this.dataTypeOptions[0].dictValue;
      this.getMonitoringItem();
    });
    // 获取数据类型
    this.getDicts("db_group_method").then((response) => {
      this.groupMethodOptions = response.data;
    });

    // getFieldInfo({ tableName: "db_uhra", columnName: 'ua' }).then((res) => {
    //   this.monitoringItemOptions = res.data;
    // });

    // 初始化查询条件
    let obj = this.$store.state.filterConditions.filterConditions;
    console.log("time", obj);
    if (obj) {
      this.baseDataParam.deviceId = obj.device;
      this.baseDataParam.datetime = obj.datetime;
      let device = this.deviceList.find(
        (f) => f.zhGuid == this.baseDataParam.deviceId
      );
      if (device) {
        this.channelList = device.channelList;
        this.baseDataParam.tdGuid = obj.channel;
        // this.baseDataParam.groupMethod = obj.selectedTable
      }
    }
  },

  watch: {
    baseDataParam: {
      handler(newForm, oldForm) {
        let obj = Object.assign({}, newForm);
        obj.channel = obj.tdGuid;
        obj.device = obj.deviceId;
        obj.datetime = obj.datetime;
        // obj.selectedTable = obj.groupMethod
        delete obj.tdGuid;
        delete obj.deviceId;
        delete obj.groupMethod;
        this.$store.commit("UPDATE_FILTER_CONDITIONS", obj);
        console.log(this.$store.state.filterConditions.filterConditions);
      },
      deep: true,
    },
  },
  methods: {
    setChannelList(id) {
      let device = this.deviceList.find((f) => f.zhGuid == id);
      if (device) {
        this.channelList = device.channelList;
        this.baseDataParam.tdGuid = device.channelList[0]?.tdGuid;
      }
    },
    syncTooltip(fromChart, toCharts) {
      // 监听 fromChart 的 mousemove 事件
      fromChart.getZr().on(
        "mousemove",
        {},
        debounce(function (params) {
          toCharts.forEach(function (chart) {
            // chart.off('updateAxisPointer'); // 移除之前的事件监听器
            // console.log(params.dataIndex)
            var pointInPixel = [params.offsetX, params.offsetY];
            var dataIndex = fromChart.convertFromPixel(
              { seriesIndex: 0 },
              pointInPixel
            )[0];
            if (dataIndex) {
              chart.dispatchAction({
                type: "showTip",
                seriesIndex: 0,
                dataIndex: dataIndex,
              });
            } else {
              chart.dispatchAction({
                type: "hideTip",
              });
            }
          });
        }, 10)
      );
      let _this = this;
      fromChart.on("magictypechanged", (event) => {
        const { currentType } = event;
        toCharts.forEach(function (chart, index) {
          const option = chart.getOption().series[0];
          console.log(option);
          chart.setOption({
            title: {
              text: option.name.split("").join("\n"),
              left: "1%",
              top: "center", // 标题水平居中
            },
            tooltip: {
              trigger: "axis", // 当鼠标悬停时显示所有折线的对应值
            },
            grid: {
              left: "5%", // 距离左边的距离
              right: "5%", // 距离右边的距离
              top: "10%", // 距离顶部的距离
              bottom: "10%", // 距离底部的距离
            },
            toolbox: {
              feature: {
                // saveAsImage: {}, // 保存为图片
                // dataView: { readOnly: false }, // 数据视图
                magicType: {
                  // 动态类型切换
                  type: ["line", "bar"], // 支持切换到折线图和柱状图
                  title: {
                    line: "切换为折线图",
                    bar: "切换为柱状图",
                  },
                },
                // restore: {} // 还原
              },
              right: 100,
            },
            legend: {
              data: ["折线1", "折线2", "折线3"], // 图例，用于区分不同的折线
            },
            xAxis: {
              type: "category",
              data: _this.chartData.timeDate,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                name: option.name, // 折线名称,
                type: currentType,
                data: option.data, // 折线数据
                itemStyle: {
                  color: "#FF7948", // 设置数据点颜色为蓝色
                },
                lineStyle: {
                  color: "#FF7948", // 设置折线颜色
                },
              },
            ],
          });
        });
      });
    },

    getMonitoringItem() {
      // this.baseDataParam.monitoringItem = ""; // 清空监测项选项
      // 根据选择的数据类获取监测项选项，例如从后端获取监测项选项列表并赋值给 monitoringItemOptions
      // 这里只是一个示例，你需要根据实际情况修改获取监测项选项的逻辑
      const dataType = this.dataTypeOptions.find(
        (f) => f.dictValue === this.baseDataParam.dataType
      );
      const filterTable = ["uhr", "ihr", "uhrj", "ihrj"];
      if (filterTable.includes(this.baseDataParam.dataType)) {
        console.log(this.baseDataParam.dataType);
        const params = {
          tableName: "db_" + this.baseDataParam.dataType + "a",
          columnName: dataType.cssClass,
        };
        getFieldInfo(params).then((res) => {
          this.monitoringItemOptions = res.data;
          console.log(this.baseDataParam.dataType);
          switch (this.baseDataParam.dataType) {
            case "ihr":
              this.monitoringItemOptions = res.data.map((item, index) => {
                if (index === 0) {
                  return { field: item.field, comment: "总畸变率" };
                } else if (index === 1) {
                  return { field: item.field, comment: "基波" };
                } else {
                  return {
                    field: item.field,
                    comment: item.field.replaceAll("Ia", "Hr"),
                  };
                }
              });
              console.log(this.monitoringItemOptions);
              break;
            case "ihrj":
              this.monitoringItemOptions = res.data.map((item, index) => {
                return { field: item.field, comment: (index + 1) * 5 + "Hz" };
              });
              console.log(this.monitoringItemOptions);
              break;
            case "uhrj":
              this.monitoringItemOptions = res.data.map((item, index) => {
                return { field: item.field, comment: (index + 1) * 5 + "Hz" };
              });
              console.log(this.monitoringItemOptions);
              break;
            // case "uhr":
            //   this.monitoringItemOptions = res.data.map((item, index) => {
            //     if (index === 0) {
            //       return { field: item.field, comment: '总畸变率' }
            //     } else if (index === 1) {
            //       return { field: item.field, comment: '基波' }
            //     } else {
            //       return { field: item.field, comment: item.field.replaceAll('Ia', 'Hr') }
            //     }
            //   })
            //   console.log(this.monitoringItemOptions)
            //   break;
          }
          this.baseDataParam.monitoringItem =
            this.monitoringItemOptions[0].field; // 默认选中第一个监测项
          this.handleSearch();
        });
      } else {
        if (this.baseDataParam.dataType == "qtsj") {
          this.monitoringItemOptions = [
            { field: "Pa,Pb,Pc", comment: "有功功率" },
            { field: "Qa,Qb,Qc", comment: "无功功率" },
            { field: "Sa,Sb,Sc", comment: "视在功率" },
            { field: "Pfa,PFb,PFc", comment: "真功率因数" },
            { field: "Cosa,Cosb,Cosc", comment: "位移功率因数" },
            { field: "bphU", comment: "电压不平衡度" },
            { field: "bphI", comment: "电流不平衡度" },
            { field: "pcFreq", comment: "频率偏差" },
          ];
          this.baseDataParam.monitoringItem =
            this.monitoringItemOptions[0].field;
        } else if (this.baseDataParam.dataType == "yxz") {
          this.monitoringItemOptions = [
            { field: "ua,ub,uc", comment: "电压有效值" },
            { field: "ia,ib,ic", comment: "电流有效值" },
          ];
          this.baseDataParam.monitoringItem =
            this.monitoringItemOptions[0].field;
        } else {
          this.monitoringItemOptions = [
            { comment: dataType.dictLabel, field: dataType.cssClass },
          ]; // 默认选中第一个监测项
          this.baseDataParam.monitoringItem =
            this.monitoringItemOptions[0].field;
        }

        this.handleSearch();
      }
    },
    handleSearch() {
      this.charComponents = [];
      this.dateKey = new Date();
      const dataType = this.dataTypeOptions.find(
        (f) => f.dictValue === this.baseDataParam.dataType
      );
      if (!this.baseDataParam.monitoringItem) {
        this.$message.error("监测项不能为空");
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "加载中...请耐心等待",
        spinner: "el-icon-loading",
        background: "rgba(225, 225, 225, 0.7)",
      });
      const filterTable = ["uhr", "ihr", "uhrj", "ihrj"];
      if (filterTable.includes(this.baseDataParam.dataType)) {
        getFlowLineData(this.baseDataParam).then((res) => {
          let title = dataType ? dataType.dictLabel : "";
          this.chartData = res.data;
          if (this.chartData) {
            this.charComponents = Object.keys(this.chartData).filter(
              (key) => key != "timeDate"
            );
            setTimeout(() => {
              this.charComponents.forEach((key) => {
                this.$refs[`chart${key}`][0].initChart({
                  title: key.toUpperCase() + "相" + title, // 折线名称,
                  data: this.chartData[key], // 折线数据
                  timeDate: this.chartData.timeDate, // 折线数据
                });
              });
              this.charComponents.forEach((key) => {
                // console.log(this.charComponents.filter(f => f !== key).map((m) => this.$refs[`chart${m}`][0].chart))
                this.syncTooltip(
                  this.$refs[`chart${key}`][0].chart,
                  this.charComponents
                    .filter((f) => f !== key)
                    .map((m) => this.$refs[`chart${m}`][0].chart)
                );
              });
            }, 500);
          }
          loading.close();
        });
      } else {
        let params = Object.assign({}, this.baseDataParam);

        if (params.datetime && params.datetime.length === 2) {
          params.startTime = params.datetime[0];
          params.endTime = params.datetime[1];
          delete params.datetime;
        }
        console.log("执行了", JSON.parse(JSON.stringify(params)));
        let obj = {
          columns: this.baseDataParam.monitoringItem,
          ...params,
        };
        console.log("执行了2", JSON.parse(JSON.stringify(obj)));
        getFlowDataBase(obj).then((res) => {
          let title = dataType ? dataType.dictLabel : "";
          this.chartData = res.data;
          if (this.chartData) {
            this.charComponents = Object.keys(this.chartData).filter(
              (key) => key != "timeDate"
            );
            console.log(this.charComponents);
            console.log(this.chartData);
            setTimeout(() => {
              this.charComponents.forEach((key) => {
                console.log(this.$refs[`chart${key}`]);
                this.$refs[`chart${key}`][0].initChart({
                  title: key.toUpperCase() + "相" + title, // 折线名称,
                  data: this.chartData[key], // 折线数据
                  timeDate: this.chartData.timeDate, // 折线数据
                });
              });
              this.charComponents.forEach((key) => {
                // console.log(this.charComponents.filter(f => f !== key).map((m) => this.$refs[`chart${m}`][0].chart))
                this.syncTooltip(
                  this.$refs[`chart${key}`][0].chart,
                  this.charComponents
                    .filter((f) => f !== key)
                    .map((m) => this.$refs[`chart${m}`][0].chart)
                );
              });
            }, 500);
          }
          loading.close();
        });
      }
    },
    setDateTime() {},
  },
};
</script>

<style lang="scss" scoped></style>
